package com.acheli.mixin;

import com.acheli.registry.config.CustomDataBus;
import com.acheli.registry.resource.DynamicResourcePack;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.IoSupplier;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceMetadata;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import software.bernie.geckolib.loading.FileLoader;

import java.io.IOException;
import java.io.InputStream;


@Mixin(FileLoader.class)
public abstract class FileLoaderMixin {
    /**
     * 定义外部模型文件的根目录（例如：./config/geckolib/models）
    /**
     * 拦截原版 getFileContents 方法，优先加载外部文件
     */
    @Redirect(
        method = "getFileContents",
        at = @At(
            value = "INVOKE",
            target = "Lnet/minecraft/server/packs/resources/ResourceManager;getResourceOrThrow(Lnet/minecraft/resources/ResourceLocation;)Lnet/minecraft/server/packs/resources/Resource;"
        )
    )
    private static Resource redirectResourceLoad(ResourceManager manager, ResourceLocation location) {
        // 尝试从外部目录加载文件
        Resource cache = null;
        CustomDataBus.dynamicResourcePackHashMap.remove(location);
        CustomDataBus.load();
        if (CustomDataBus.dynamicResourcePackHashMap.containsKey(location)) {
            System.out.println("EXIST" + location);
            DynamicResourcePack dynamicResource = CustomDataBus.dynamicResourcePackHashMap.get(location);
            // 创建输入流供应商（直接读取外部文件）
            IoSupplier<InputStream> streamSupplier = dynamicResource::getInputStream;
            IoSupplier<ResourceMetadata> metaSupplier = () -> ResourceMetadata.EMPTY;
            // 返回自定义 Resource 实例
            cache = new Resource(
                    dynamicResource,
                    streamSupplier,
                    metaSupplier // 空元数据
            );
            return cache;
        }

        try {
             return manager.getResourceOrThrow(location);
        } catch (IOException ignored) {

        }


        // 回退到原版资源加载
        return  cache;
    }

}